package Presenter;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;
import Models.FGIView;

public class FGIViewPresenter extends AbstractPresenter<FGIView> {
	final String SINGLEITEM = "fgiView";
	final String MULTIITEM = "fGIViews";
	
	public ArrayList<FGIView> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public FGIView tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public FGIView createItemFromJSONObject(JSONObject jsonObject){
		FGIView item = new FGIView();
		try{
			if(!jsonObject.isNull("fgiid")){
				item.setFgiID(jsonObject.getInt("fgiid"));
				item.setFgiDescription(jsonObject.getString("FGIDescription"));
				item.setPendingQty(jsonObject.getInt("fGIQtyAllocated"));
				item.setFgiQtyOnHand(jsonObject.getLong("FGIQtyOnHand"));
				item.setServingVesselVolume(jsonObject.getDouble("servingTankVolume"));
				item.setVersion(jsonObject.getLong("version"));
				item.setFgiPrice(jsonObject.getDouble("FGIPriceCode"));
				
				BeerViewPresenter beerPresenter = new BeerViewPresenter();
				JSONObject jsonBeer = jsonObject.getJSONObject("FGIBeerID");
				item.setBeer(beerPresenter.createItemFromJSONObject(jsonBeer));
				
				PackageTypePresenter ptPresenter = new PackageTypePresenter();
				JSONObject jsonPT = jsonObject.getJSONObject("FGIPackageID");
				item.setPackageType(ptPresenter.createItemFromJSONObject(jsonPT));
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(FGIView item){
		try{
			JSONObject json = new JSONObject();
			json.put("fgiid", item.getFgiID());
			json.put("FGIDescription", item.getFgiDescription());
			json.put("fGIQtyAllocated", item.getPendingQty());
			json.put("FGIQtyOnHand", item.getFgiQtyOnHand());
			json.put("servingTankVolume", item.getServingVesselVolume());
			json.put("version", item.getVersion());
			json.put("FGIPriceCode", item.getFgiPrice());

			BeerViewPresenter beerPresenter = new BeerViewPresenter();
			json.put("FGIBeerID", beerPresenter.createJSON(item.getBeer()));
			
			PackageTypePresenter ptPresenter = new PackageTypePresenter();
			json.put("FGIPackageID", ptPresenter.createJSON(item.getPackageType()));
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public FGIView getEmptyEntity(){
		FGIView entity = new FGIView();
		return entity;
	}
}
